﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using System.IO;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.Framework.Controls;

using PlanningGIS.CoordCovert.model;
using DevComponents.DotNetBar;
using PlanningGIS.Framework;
using PlanningGIS.Engine.Controls;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Convertor;

namespace PlanningGIS.CoordCovert.form
{
    public partial class Frm7ParaConvert : Office2007Form
    {
        private IApplication m_Application;
        
        private ISpatialReference pSrIn;
        private ISpatialReference pSrOut;

        private string folder;
        private const string DEFAULT_FILE_NAME = "param7_def.txt";
        public Frm7ParaConvert(IApplication value)
        {
            InitializeComponent();
            m_Application = value;
        }

        ///// <summary>
        ///// 日志操作委托事件
        ///// </summary>
        //public WriteLog2 WriteLogEvent { get; set; }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                IList<IFeatureClass> fclasslist = new List<IFeatureClass>();
                OpenDataDialog addData = new OpenDataDialog();

                addData.OnOkClick = delegate
                {
                    List<IDataNode> datanodes = addData.GetSelectNode<IDataNode>();
                    foreach (IDataNode datanode in datanodes)
                    {
                        if (datanode is FeatureClassNode)
                        {
                            fclasslist.Add(datanode.Open() as IFeatureClass);
                        }
                        else if (datanode is DatasetNode)
                        {
                            IEnumDataset datasetenum = datanode.Open().Subsets;
                            IDataset dataset = datasetenum.Next();
                            while (dataset != null)
                            {
                                fclasslist.Add(dataset as IFeatureClass);
                                dataset = datasetenum.Next();
                            }
                        }
                    }
                    foreach (IFeatureClass featureClass in fclasslist)
                    {

                        ListViewItem pListViewItem = new ListViewItem(((IDataset)featureClass).BrowseName);

                        pListViewItem.Tag = featureClass;
                        pListViewItem.Checked = true;
                        this.listView1.Items.Add(pListViewItem);

                    }
                    addData.Close();
                };
                addData.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox(ex.Message);
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listView1.Items.Count == 0) return;
                if (this.listView1.SelectedItems.Count == 0) return;

                foreach (ListViewItem pListViewItem in this.listView1.SelectedItems)
                {
                    this.listView1.Items.Remove(pListViewItem);
                }
                //if (this.listView1.Items.Count == 0) this.listView1.Tag = null;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("移除失败：" + ex.Message);
            }
        }

        private void FrmAffine4Para_Load(object sender, EventArgs e)
        {
            txtDX.KeyPress += ControlVerify.txtDoubleBox_KeyPress;
            txtDY.KeyPress += ControlVerify.txtDoubleBox_KeyPress;
            txtDZ.KeyPress += ControlVerify.txtDoubleBox_KeyPress;

            txtRX.KeyPress += ControlVerify.txtDoubleBox_KeyPress;
            txtRY.KeyPress += ControlVerify.txtDoubleBox_KeyPress;
            txtRZ.KeyPress += ControlVerify.txtDoubleBox_KeyPress;

            txtK.KeyPress += ControlVerify.txtDoubleBox_KeyPress;

            #region 读取默认参数
            folder = AppConfig.SysFolder + "\\parameter";
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            string fileName = folder + "\\" + DEFAULT_FILE_NAME;
            if (!File.Exists(fileName)) File.Create(fileName);

            try
            {
                StreamReader streamReaderr = null;
                streamReaderr = File.OpenText(fileName);

                string txt = "";
                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtDX.Text = txt;
                }

                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtDY.Text = txt;
                }

                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtDZ.Text = txt;
                }

                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtRX.Text = txt;
                }

                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtRY.Text = txt;
                }

                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtRZ.Text = txt;
                }

                txt = streamReaderr.ReadLine();
                if (StringHelper.CanConvert2Double(txt))
                {
                    txtK.Text = txt;
                }
            }
            catch { }
            #endregion


        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 进度条相关

        private void setAllPgbMax(int max)
        {
            //this.Width = this.Width + progressBarAll.Width;
            progressBarAll.Maximum = max;
            progressBarAll.Minimum = 0;
            progressBarAll.Value = 0;
            Application.DoEvents();
        }

        private void setAllPgbCurrent(int current)
        {
            if (current <= progressBarAll.Maximum)
            {
                progressBarAll.Value = (int)current;

                double dRate = current * 100.0 / progressBarAll.Maximum;
                int iRate = (int)Math.Floor(dRate);
                progressBarAll.TextVisible = true;
                progressBarAll.Text = "总进度：" + current.ToString() + "/" + progressBarAll.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                //dataGridViewX1.UseWaitCursor = true;
            }
            else
            {
                progressBarAll.Value = (int)progressBarAll.Maximum;
                progressBarAll.TextVisible = false;
                //dataGridViewX1.UseWaitCursor = false;
            }
            progressBarAll.Update();
            if (progressBarAll.Maximum < 200)
                Application.DoEvents();
            else
                if (current % (progressBarAll.Maximum / 100) == 0) Application.DoEvents();
        }

        #endregion

        private void btnConvert_Click(object sender, EventArgs e)
        {
            List<IFeatureClass> pFeatClses = new List<IFeatureClass>();

            foreach (ListViewItem pListViewItem in this.listView1.Items)
            {
                if (pListViewItem.Checked && pListViewItem.Tag != null && pListViewItem.Tag is IFeatureClass)
                {
                    pFeatClses.Add(pListViewItem.Tag as IFeatureClass);
                }
            }

            if (pFeatClses.Count == 0)
            {
                MsgHelper.ShowWarningMsgbox("请设置需要转换的数据！");
                return;
            }

            if (txtDX.Text.Trim() == "" || txtDY.Text.Trim() == "" || txtDZ.Text.Trim() == "" ||
                txtRX.Text.Trim() == "" || txtRY.Text.Trim() == "" || txtRZ.Text.Trim() == "" ||
                txtK.Text.Trim() == "")
            {
                MsgHelper.ShowWarningMsgbox("请设置参数！");
                return;
            }
            try
            {
                double dx, dy, dz, rx, ry, rz, k;
                try
                {
                    dx = Double.Parse(txtDX.Text.Trim());
                    dy = Double.Parse(txtDY.Text.Trim());
                    dz = Double.Parse(txtDZ.Text.Trim());
                    rx = Double.Parse(txtRX.Text.Trim());
                    ry = Double.Parse(txtRY.Text.Trim());
                    rz = Double.Parse(txtRZ.Text.Trim());
                    k = Double.Parse(txtK.Text.Trim());

                }
                catch (Exception ex)
                {
                    MsgHelper.ShowWarningMsgbox("读取参数失败：" + ex.Message + "/n请设置正确的参数！");
                    return;
                }

                this.Cursor = Cursors.WaitCursor;

                Convert7Para convert7Para = new Convert7Para();
                convert7Para.DX = dx;
                convert7Para.DY = dy;
                convert7Para.DZ = dz;
                convert7Para.RX = rx;
                convert7Para.RY = ry;
                convert7Para.RZ = rz;
                convert7Para.K = k;
                convert7Para.SrIn = pSrIn;
                convert7Para.SrOut = pSrOut;
                convert7Para.FeatClses = pFeatClses;
                convert7Para.SetProcessBarMax = setAllPgbMax;
                convert7Para.SetProcessBarCurrent = setAllPgbCurrent;

                btnConvert.Enabled = false;
                btnCancel.Enabled = false;

                if (convert7Para.Operate())
                {
                    MsgHelper.ShowInfomationMsgbox("转换完毕！");
                }
                else
                {
                    MsgHelper.ShowErrorMsgbox("转换失败，具体信息请参看日志！");
                }
            }
            catch(Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("转换失败：" + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                btnConvert.Enabled = true;
                btnCancel.Enabled = true;
                progressBarAll.Value = 0;
                progressBarAll.Text = "";
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "导入参数文件";
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.Multiselect = false;
            openFileDialog1.Filter = "参数文件(*.txt)|*.txt";
            openFileDialog1.InitialDirectory = folder;

            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                if (openFileDialog1.FileName == "") return;
                try
                {
                    StreamReader streamReaderr = null;
                    streamReaderr = File.OpenText(openFileDialog1.FileName);

                    string txt = "";
                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtDX.Text = txt;
                    }

                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtDY.Text = txt;
                    }

                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtDZ.Text = txt;
                    }

                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtRX.Text = txt;
                    }

                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtRY.Text = txt;
                    }

                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtRZ.Text = txt;
                    }

                    txt = streamReaderr.ReadLine();
                    if (StringHelper.CanConvert2Double(txt))
                    {
                        txtK.Text = txt;
                    }

                    MsgHelper.ShowInfomationMsgbox("导入成功！");
                }
                catch(Exception ex) 
                {
                    MsgHelper.ShowWarningMsgbox("导入失败：" + ex.Message);
                }

            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Title = "导出参数文件";
            saveFileDialog1.Filter = "参数文件(*.txt)|*.txt";
            saveFileDialog1.InitialDirectory = folder;

            try
            {
                if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    string strTextpath = saveFileDialog1.FileName;
                    if (File.Exists(strTextpath)) File.Delete(strTextpath);
                    StreamWriter sw = File.CreateText(strTextpath);
                    sw.WriteLine(txtDX.Text);
                    sw.WriteLine(txtDY.Text);
                    sw.WriteLine(txtDZ.Text);
                    sw.WriteLine(txtRX.Text);
                    sw.WriteLine(txtRY.Text);
                    sw.WriteLine(txtRZ.Text);
                    sw.WriteLine(txtK.Text);
                    sw.Close();

                    MsgHelper.ShowInfomationMsgbox("导出成功！");
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
            }
        }

        private ISpatialReference GetSpatialReferenceFromPrj(string strPrjName)
        {
            if (strPrjName.Trim().Length == 0) return null;
            ISpatialReference pSR = null;
            ISpatialReferenceFactory pSRFactory = new SpatialReferenceEnvironmentClass();
            try
            {
                pSR = pSRFactory.CreateESRISpatialReferenceFromPRJFile(strPrjName);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("空间坐标参考文件已经破坏或者不支持，请检查：" + ex.Message);
                return null;
            }
            return pSR;
        }

        private void btnSrIn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Title = "选择空间参考文件";
            openDlg.Filter = "坐标文件|*.prj";
            openDlg.Multiselect = false;
            if (openDlg.ShowDialog(this) == DialogResult.OK)
            {
                pSrIn = GetSpatialReferenceFromPrj(openDlg.FileName.Trim());
                txtSrIn.Text = pSrIn.Name;
            }
        }

        private void btnSrOut_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Title = "选择空间参考文件";
            openDlg.Filter = "坐标文件|*.prj";
            openDlg.Multiselect = false;
            if (openDlg.ShowDialog(this) == DialogResult.OK)
            {
                pSrOut = GetSpatialReferenceFromPrj(openDlg.FileName.Trim());
                txtSrOut.Text = pSrOut.Name;
            }
        }
    }
}
